package com.systop.ltbook.book.press.webapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.systop.cms.utils.PageUtil;
import com.systop.core.ApplicationException;
import com.systop.core.dao.support.Page;
import com.systop.core.webapp.struts2.action.ExtJsCrudAction;
import com.systop.ltbook.book.press.model.Press;
import com.systop.ltbook.book.press.service.PressManager;

/**
 * <code>Press</code>对象的struts2 action。
 * 
 * @author DU
 */
@SuppressWarnings({ "serial", "unchecked" })
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class PressAction extends ExtJsCrudAction<Press, PressManager> {

	/**
	 * 出版社查询列表
	 */
	@Override
	public String index() {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		StringBuffer hql = new StringBuffer("from Press p where 1=1 ");
		List args = new ArrayList();

		// 按出版社名称查询
		if (StringUtils.isNotBlank(getModel().getName())) {
			hql.append(" and p.name like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getName()));
		}

		hql.append(" order by p.charName");
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		return INDEX;
	}

	/**
	 * 保存图书
	 */
	@Override
	public String save() {
		try {
			if (extractId(getModel()) != null) {
				getManager().getDao().evict(getModel());
			}
			getManager().save(getModel());
			return SUCCESS;
		} catch (ApplicationException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
	}

	/**
	 * 删除出版社
	 */
	@Override
	public String remove() {
		Press press = getManager().get(getModel().getId());
		if (press.getBooks().size() != 0) {
			addActionError("该出版社涉及图书信息，不能删除！");
			return INDEX;
		}

		return super.remove();
	}

	public String reSavePress() {
		String hql = "from Press p order by p.id";
		List<Press> presses = getManager().query(hql);
		for (Press p : presses) {
			p.setName(StringUtils.trim(p.getName()));
			getManager().save(p);
		}
		return SUCCESS;
	}
}
